<template>
  <div class="wrapper-list">
    <!-- 条件区 -->
    <div class="wrapper-condition">
      <el-form :inline="true" label-position="left" label-width="80px" size="small">
        <el-form-item>
          <el-button type="success" icon="Plus" @click="onAdd()">上传新文件</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表区 -->
    <div class="wrapper-table">
      <el-table
        v-loading="flagLoading"
        :data="tblDataList"
        :header-cell-style="{ 'text-align': 'center' }"
        row-key="id"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column align="center" width="100" label="缩略图">
          <template #default="scope">
            <el-link v-if="isImage(scope.row.extName)" :underline="false" @click="previewFile(scope.row)">
              <el-image style="width: 80px; height: 60px" :src="setImgUrl(scope.row.uuid)" fit="fill" />
            </el-link>
          </template>
        </el-table-column>

        <el-table-column label="文件名（服务器端）">
          <template #default="scope">
            {{ scope.row.fileName + scope.row.extName }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="文件大小" width="100" prop="fileSize" :formatter="showFileSize" />

        <el-table-column align="center" label="上传人" width="100" prop="adminName" />

        <el-table-column align="center" label="上传时间" width="150" prop="dtUpload" />

        <el-table-column align="center" width="160" label="操作">
          <template #default="scope">
            <div class="wrapper-op">
              <a
                class="ibtn copy"
                title="拷贝文件URL"
                size="small"
                type="success"
                :data-clipboard-text="setCopyTxt(scope.row.uuid)"
                data-clipboard-action="copy"
                @click="onCopy()"
              >
                <el-icon><DocumentCopy /></el-icon>
              </a>
              <a title="下载" class="ibtn ibtn-download" @click="onDownload(scope.row.uuid)">
                <el-icon><Download /></el-icon>
              </a>
              <a title="编辑" class="ibtn ibtn-edit" @click="onEdit(scope.row)">
                <el-icon><Edit /></el-icon>
              </a>
              <a title="删除" class="ibtn ibtn-del" @click="onDelete(scope.row.uuid)">
                <el-icon><Delete /></el-icon>
              </a>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区 -->
    <div class="wrapper-pager">
      <el-pagination
        :currentPage="pageCurrent"
        :pageSizes="pageSizeArrray"
        :pageSize="pageSize"
        :total="recordCount"
        :pageCount="pageCount"
        background
        layout="total, prev, pager, next, jumper, sizes"
        @sizeChange="onSizeChange"
        @currentChange="onCurrentChange"
      />
    </div>

    <!-- 弹出框 显示图片 -->
    <el-dialog title="预览图片" v-model="flagDialogPreview">
      <el-image :src="urlPreviewImg" style="height: 400px" fit="contain">
        <template #error>
          <el-icon color="#ff0000"><WarningFilled /></el-icon>
        </template>
      </el-image>
      <template #footer>
        <el-button @click="flagDialogPreview = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 弹出框 编辑文件信息 -->
    <el-dialog title="修改文件信息" v-model="flagDialogEdit">
      <el-image :src="previewFile(formDataFile)" style="height: 150px" fit="contain">
        <template #error>
          <el-icon color="#ff0000"><WarningFilled /></el-icon>
        </template>
      </el-image>
      <el-form :model="formDataFile">
        <el-form-item label="标签">
          <el-input v-model="formDataFile.tag" autocomplete="off" placeholder="请输入标签..." />
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="formDataFile.remark" autocomplete="off" placeholder="请输入文件简介..." />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="flagDialogEdit = false">取消</el-button>
        <el-button type="primary" @click="onSave()">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getAdminId } from '@/utils/common'
import { formatFileSize } from '@/utils/file'
import { isImageByExt } from '@/utils/validate'
import { resolveBlob, aryBuffer2Base64 } from '@/utils/file'
// import handleClipboard from '@/utils/clipboard'
import { toastSuccess, toastError } from '@/utils/toast'

import { ElMessageBox } from 'element-plus'
import Clipboard from 'clipboard'

import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'UlFileListPageView',
  setup() {
    // https://xzqtsg.info/api-public/file/image/
    const urlPrefixShow = ref(process.env.VUE_APP_URL_UPLOAD_SHOW_UUID)
    const typeUploader = ref('Admin')
    const idAdmin = ref(0)
    const tblDataList = ref([])
    const flagLoading = ref(true)
    const pageCurrent = ref(1)
    const pageSize = ref(20)
    const pageSizeArrray = ref([10, 20, 30, 40])
    const recordCount = ref(0)
    const pageCount = ref(1)
    const flagDialogPreview = ref(false)
    const flagDialogEdit = ref(false)
    const formDataFile = ref({})
    const urlPreviewImg = ref('')
    const imgPreview = ref('')

    // 获取当前登录管理员id
    const getIdAdmin = () => {
      idAdmin.value = getAdminId()
    }
    // 上传新文件
    const onAdd = () => {}
    // 显示文件，如果是图片显示缩略图，如果是文件，显示图标
    const previewFile = (file) => {
      // console.log('previewFile file', file)
      flagDialogPreview.value = true
      if (!file || !file.mimeType) return
      // const uuid = file.uuid
      const mimeType = file.mimeType
      if (mimeType.startsWith('image/')) {
        urlPreviewImg.value = urlPrefixShow.value + file.uuid
      } else {
        urlPreviewImg.value = ''
      }
    }
    // 显示图片缩略图
    const setImgUrl = (uuid) => {
      return urlPrefixShow.value + uuid
    }
    const setCopyTxt = (uuid) => {
      return urlPrefixShow.value + uuid
    }
    const setPreviewImgUrl = (file) => {
      if (!file || !file.mimeType) return
      let url = '<img src="'
      if (file.mimeType.startsWith('image/')) {
        url += urlPrefixShow.value + file.uuid
        url += '" width="300px" height="300px" alt="图片预览" />'
        imgPreview.value = url
      } else {
        imgPreview.value = ''
      }
    }
    const showFileSize = (val) => {
      return formatFileSize(val.fileSize)
    }
    // 根据uuid显示图像文件
    const showImageByUuid = (uuid) => {
      if (!uuid || uuid === '') return
      store
        .dispatch('sys_ul_file/showImageByUuid', uuid)
        .then((response) => {
          console.log('showImageByUuid response', response)
          return aryBuffer2Base64(response)
        })
        .catch(() => {})
    }
    // 点击编辑按钮
    const onEdit = (file) => {
      flagDialogEdit.value = true
      formDataFile.value = file
    }
    // 编辑完成后保存
    const onSave = () => {
      flagDialogEdit.value = false
      if (!formDataFile.value) return
      const paramsJson = {
        Id: formDataFile.value.id,
        Tag: formDataFile.value.Tag,
        FileName: formDataFile.value.FileName,
        Remark: formDataFile.value.Remark,
      }
      store
        .dispatch('sys_ul_file/patchSomething', paramsJson)
        .then(() => {
          flagDialogEdit.value = false
          toastSuccess('编辑成功！')
          listPage()
        })
        .catch(() => {
          flagDialogEdit.value = false
        })
    }
    // 点击下载按钮
    const onDownload = (uuid) => {
      if (!uuid || uuid === '') return
      store
        .dispatch('sys_ul_file/downloadEntity', uuid)
        .then((response) => {
          resolveBlob(response)
        })
        .catch(() => {})
    }
    // 点击拷贝链接按钮
    const onCopy = () => {
      // console.log('onCopy text:', text)
      // const url = urlPrefixShow.value + text
      // console.log('onCopy url:', url)
      let clipboard = new Clipboard('.copy')
      clipboard.on('success', (e) => {
        // console.log('复制成功', e)
        toastSuccess('[ ' + e.text + ' ] 拷贝成功！')
        clipboard.destroy()
      })
      clipboard.on('error', (e) => {
        // 不支持复制
        console.log('该浏览器不支持自动复制', e)
        toastError('拷贝失败！该浏览器不支持自动复制！')
        clipboard.destroy()
      })
    }
    // 点击删除按钮
    const onDelete = (uuid) => {
      ElMessageBox.confirm('确定要删除该文件吗？', '删除警告', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          store
            .dispatch('sys_ul_file/delByUuid', uuid)
            .then((response) => {
              if (response.data.statusCode === '20400') {
                toastSuccess(response.data.message)
              }
              listPage()
            })
            .catch(() => {})
        })
        .catch(() => {})
    }
    // 得到所有管理员上传到服务器上的文件分页数据
    const listPage = () => {
      flagLoading.value = true
      const paramsJson = {
        PageCurrent: pageCurrent.value,
        PageSize: pageSize.value,
      }
      store
        .dispatch('sys_ul_file/listPage', paramsJson)
        .then((response) => {
          flagLoading.value = false
          tblDataList.value = response.ListData
          recordCount.value = Number(response.RecordCount)
          pageCount.value = response.PageCount
        })
        .catch(() => {
          flagLoading.value = false
        })
    }
    // 点击每页记录数大小下拉菜单
    const onSizeChange = (val) => {
      pageSize.value = val
      listPage()
    }
    // 点击分页页码
    const onCurrentChange = (val) => {
      pageCurrent.value = val
      listPage()
    }
    const isImage = (ext) => {
      return isImageByExt(ext)
    }

    onMounted(() => {
      getIdAdmin()
      listPage()
    })

    return {
      urlPrefixShow,
      typeUploader,
      idAdmin,
      tblDataList,
      flagLoading,
      pageCurrent,
      pageSize,
      pageSizeArrray,
      recordCount,
      pageCount,
      flagDialogPreview,
      flagDialogEdit,
      formDataFile,
      urlPreviewImg,
      imgPreview,

      getIdAdmin,
      onAdd,
      previewFile,
      setImgUrl,
      setCopyTxt,
      setPreviewImgUrl,
      showImageByUuid,
      showFileSize,
      onEdit,
      onSave,
      onDownload,
      onCopy,
      onDelete,
      listPage,
      onSizeChange,
      onCurrentChange,
      isImage,
    }
  },
})
</script>

<style lang="scss" scoped>
.el-button + .el-button {
  margin-left: 2px;
}
</style>
